package com.sptpc.springbootmybatis.handler;

import com.sptpc.springbootmybatis.util.OrderState;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class OrderStateTypeHandler extends BaseTypeHandler<OrderState> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, OrderState parameter, JdbcType jdbcType) throws SQLException {
//        默认情况下，枚举类会给所有的枚举变量一个默认的排序，该次序从0开始，类似于数组的下标，
//        而ordinal()方法就是获取这个次序（或者说下标）
        ps.setInt(i, parameter.ordinal());
    }

    @Override
    public OrderState getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return parseOrderState(rs.getInt(columnName));
    }

    @Override
    public OrderState getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return parseOrderState(rs.getInt(columnIndex));
    }

    @Override
    public OrderState getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return parseOrderState(cs.getInt(columnIndex));
    }

    private OrderState parseOrderState(int i){
        return OrderState.values()[i];
    }
}
